<template>
  <!-- 新增编辑弹窗 -->
  <el-drawer
    :title="dialogTitle"
    :visible.sync="isShowDialog"
    direction="ltr"
    :close-on-click-modal="false"
    custom-class="demo-drawer"
    ref="drawer"
    size="60%">
    <!-- 具体form表单 -->
    <div class="demo-drawer__content">
      <el-form label-suffix="：" label-position="right" ref="form" :rules="rules" :model="currentRow" label-width="140px"
               class="work-point-form">
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item title="监测对象信息" name="监测对象信息">
            <el-form-item label="监测项目" required style="width: 100%">
              <p style="font-weight: 600">{{ currentRow.projectName }}</p>
            </el-form-item>
            <el-form-item label="类型" required prop="slopeDamageType" v-if="disabled">
              <el-radio-group v-model="currentRow.slopeDamageType" @change="isSlopeDamageType()">
                <el-radio-button label="1">边坡</el-radio-button>
                <el-radio-button label="2">地灾</el-radio-button>
                <el-radio-button label="3">桥梁</el-radio-button>
              </el-radio-group>

            </el-form-item>
            <el-form-item label="监测对象名称" required prop="name" >
              <el-input :disabled="disabled"
                        v-model.trim="currentRow.name"
                        placeholder="输入监测对象名称"

                        clearable
              ></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="disabled?12:0">
                <el-form-item :label="this.currentRow.label" prop="bianpiType">
                  <el-select
                    @change="getSlopeInfo"
                    v-model.trim="currentRow.slopeDamageId"
                    clearable
                    :placeholder="this.currentRow.placeholder">
                    <el-option
                      v-for="item in slopeDamageList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="disabled?12:24">
                <el-form-item label="监测对象区域" prop="areaId">
                  <region-unit v-model="currentRow.areaId" :key="currentRow.areaId"></region-unit>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input
                    :disabled="disabled"
                    v-model.trim="currentRow.longitude"
                    placeholder="输入经度"
                    type="number"
                    :maxlength="50"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input
                    :disabled="disabled"
                    v-model.trim="currentRow.latitude"
                    placeholder="输入纬度"
                    type="number"
                    :maxlength="50"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="起止时间">
              <el-date-picker
                value-format="timestamp"
                v-model="timerArray"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="备注" style="width: 100%">
              <el-input
                type="textarea"
                :maxlength="100"
                v-model="currentRow.remark"
                placeholder="备注"
              ></el-input>
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="监测对象照片" name="监测对象照片">
            <el-tooltip v-if="currentRow.picList.length >= 15" class="item" effect="dark" content="最多上传15张图片"
                        placement="top-start">
              <el-button class="is-disabled" size="small" type="primary">点击上传</el-button>
            </el-tooltip>
            <upload-img v-else trigger="button" avatar :size-limit="5" @update="setFormImg"></upload-img>
            <el-form :model="currentRow" ref="imgForm" class="imgFrom" :rules="imgFormRules" size="small">
              <el-table border :data="currentRow.picList" class="m-t-24" style="height: 500px;overflow: auto">
                <el-table-column label="图片名称">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="`picList.${scope.$index}.name`"
                      :rules="imgFormRules.name">
                      <el-input
                        v-model="scope.row.name"
                        placeholder="请输入图片名称"
                        :maxlength="20"
                        style="width: 100%"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="拍摄时间" width="240">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="`picList.${scope.$index}.time`"
                      :rules="imgFormRules.time">
                      <el-date-picker
                        v-model="scope.row.time"
                        type="datetime"
                        value-format="timestamp"
                        placeholder="选择拍摄时间">
                      </el-date-picker>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="图片" width="110">
                  <template slot-scope="scope">
                    <el-image
                      style="width: 60px; height: 60px"
                      fit="scale-down"
                      :src="constUrl + scope.row.url"
                    ></el-image>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      class="delete_button"
                      @click="handleDeleteImg(scope.$index)">删除
                    </el-button>
                    <el-button
                      type="text"
                      class="up_button"
                      @click="upImage(scope.$index,false)">向上
                    </el-button>
                    <el-button
                      type="text"
                      class="top_button"
                      @click="upImage(scope.$index,true)">置顶
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-collapse-item>
          <el-collapse-item title="监测对象视频" name="监测对象视频">
            <el-tooltip v-if="currentRow.videoList.length >= 2" class="item" effect="dark" content="最多上传15张图片"
                        placement="top-start">
              <el-button class="is-disabled" size="small" type="primary">点击上传</el-button>
            </el-tooltip>
            <upload-video v-else trigger="button" avatar :size-limit="5" @update="setFormVideo"></upload-video>
            <el-form :model="currentRow" ref="imgForm" class="imgFrom" :rules="videoFormRules" size="small">
              <el-table border :data="currentRow.videoList" class="m-t-24" style="height: 500px;overflow: auto">
                <el-table-column label="视频名称">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="`videoList.${scope.$index}.name`"
                      :rules="videoFormRules.name">
                      <el-input
                        v-model="scope.row.name"
                        placeholder="请输入视频名称"
                        :maxlength="20"
                        style="width: 100%"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="拍摄时间" width="240">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="`videoList.${scope.$index}.time`"
                      :rules="videoFormRules.time">
                      <el-date-picker
                        v-model="scope.row.time"
                        type="datetime"
                        value-format="timestamp"
                        placeholder="选择拍摄时间">
                      </el-date-picker>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="视频" width="320">
                  <template slot-scope="scope">
                    <video width="300" height="200" controls>
                      <source :src="constUrl + scope.row.url" type="video/mp4">
                    </video>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      class="delete_button"
                      @click="handleDeleteVideo(scope.$index)">删除
                    </el-button>
                    <el-button
                      type="text"
                      class="up_button"
                      @click="upVideo(scope.$index,false)">向上
                    </el-button>
                    <el-button
                      type="text"
                      class="top_button"
                      @click="upVideo(scope.$index,true)">置顶
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>
    <!-- 操作按钮 -->
    <div class="demo-drawer__footer">
      <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
      <el-button class="common_btn-defalut" type="primary" @click="validateForm">确定</el-button>
    </div>
  </el-drawer>
</template>

<script>
import RegionUnit from "@/components/region-unit";
import {workPointAdd, workPointUpdate} from "@/services/model/project-info";
import {store} from "../work-point.store";
import DoubleThree from "@/directives/double-three";
import UploadImg from "@/components/upload-img";
import UploadVideo from "@/components/upload-video";
import constUrl from "@/services/env";
//边坡档案下拉选择列表
import {getSlope, getDamage} from "@/services/model/road-mgmt";
import {getBridge} from "@/services/model/bridge-info";

export default {
  components: {RegionUnit, UploadImg,UploadVideo},
  props: [// 监测对象类型下拉
    "slopeList", "damageList", "bridgeList"
  ],
  // 最多输入三位小数
  directives: {DoubleThree},
  data() {
    return {
      slopeDamageList: [],
      activeName: '监测对象信息',
      // 控制input是否禁用
      // form表单校验规则
      rules: {
        name: [{required: true, message: "请输入监测对象名称"},{ max: 35, message: "最多只能输入35个字符", trigger: "blur" }]
      }, // 表单校验的规则
      imgFormRules: {
        name: {required: true, message: "请输入图片名称"},
        time: {required: true, message: "请选择拍摄时间"},
      },
      videoFormRules: {
        name: {required: true, message: "请输入视频名称"},
        time: {required: true, message: "请选择拍摄时间"},
      },
      isShowDialog: false, // 是否显示弹窗
      currentRow: {
        name: "",
        startEndPileInfo: {},
        picList: [],
        videoList: [],
      }, // 新增数据
      // 绑定的时间数组
      timerArray: [],
      constUrl,
      isShowItem: true,
    };
  },
  computed: {
    // 弹窗的title
    dialogTitle() {
      return this.currentRow.id ? "编辑监测对象" : "新增监测对象";
    },
    projectDetail() {
      return store.projectInfo;
    },
    disabled() {
      //判断监测项目是否有管养单位，没有管养单位表示普通监测项目。
      return store.projectInfo.roadId && store.projectInfo.deptTreeId ? true : false
    },
  },
  methods: {
    upImage(index, top) {
      let list = this.currentRow.picList
      if (top) {
        list.unshift(list[index]);//先把置顶元素放在最前面
        list.splice(index + 1, 1)//多了一个元素，删除index+1的原本的元素
      } else {
        list[index] = list.splice(index - 1, 1, list[index])[0];
      }
      this.currentRow.picList = list
    },
    upVideo(index, top) {
      let list = this.currentRow.videoList
      if (top) {
        list.unshift(list[index]);//先把置顶元素放在最前面
        list.splice(index + 1, 1)//多了一个元素，删除index+1的原本的元素
      } else {
        list[index] = list.splice(index - 1, 1, list[index])[0];
      }
      this.currentRow.videoList = list
    },
    isSlopeDamageType(item) {
      if (item !== '1') {
        this.currentRow.name = '';
        this.currentRow.longitude = '';
        this.currentRow.latitude = '';
        this.currentRow.slopeDamageId = ''
      }

      if (this.currentRow.slopeDamageType == 1) {
        this.slopeDamageList = this.slopeList
        this.currentRow.placeholder = '请选择边坡'
        this.currentRow.label = '边坡'

      } else if (this.currentRow.slopeDamageType == 2) {
        this.slopeDamageList = this.damageList
        this.currentRow.placeholder = '请选择地灾'
        this.currentRow.label = '地灾'
      } else if (this.currentRow.slopeDamageType == 3) {
        this.slopeDamageList = this.bridgeList
        this.currentRow.placeholder = '请选择桥梁'
        this.currentRow.label = '桥梁'
      }
    },
    // 获取边坡信息
    async getSlopeInfo(val) {
      this.currentRow.name = '';
      this.currentRow.longitude = '';
      this.currentRow.latitude = '';
      if (val == '') {
        return
      }
      let action
      if (this.currentRow.slopeDamageType == 1) {
        action = getSlope
      } else if (this.currentRow.slopeDamageType == 2) {
        action = getDamage
      } else if (this.currentRow.slopeDamageType == 3) {
        action = getBridge
      }
      let res = await action({id: val});
      let bianPo = res.data;
      this.currentRow.name = bianPo.name;
      this.currentRow.longitude = bianPo.longitude;
      this.currentRow.latitude = bianPo.latitude;
      // 解决表单验证名字一栏的问题
      this.rules.name.required = false;
    },
    // 删除图片
    handleDeleteImg(index) {
      this.currentRow.picList.splice(index, 1);
    },
    // 删除视频
    handleDeleteVideo(index) {
      this.currentRow.videoList.splice(index, 1);
    },
    // 上传成功后处理图片
    setFormImg(path) {
      let item = {
        name: "",
        time: "",
        url: path,
      };
      this.currentRow.picList.push(item);
    },
    setFormVideo(path) {
      let item = {
        name: "",
        time: "",
        url: path,
      };
      this.currentRow.videoList.push(item);
    },
    // 表单提交
    validateForm() {
      new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const [startTime, endTime] = this.timerArray;
            this.currentRow = {...this.currentRow, startTime, endTime};
            this.submitData();
          }
        });
      });
    },
    // 新增编辑提交数据
    async submitData() {
      // 根据ID判断使用新增还是编辑
      let action = this.currentRow.id ? workPointUpdate : workPointAdd;
      let res = await action(this.currentRow);
      if (res.code === 200) {
        this.$notify({
          type: "success",
          title: "提示",
          message: this.currentRow.id ? "修改成功" : "添加成功",
        });
        this.isShowDialog = false;
        this.$emit("update");
        return true;
      }
    },
    // 新增数据
    handleAdd() {
      this.activeName = '监测对象信息'
      const projectId = store.projectInfo?.id;
      if (!projectId) {
        this.$notify({
          title: "提示",
          message: "项目查询失败，请重新进入",
          type: "error",
        });
        return false;
      }
      this.timerArray = [];
      // 数据
      this.currentRow = {
        projectName: store.projectInfo?.name,
        deptTreeId: store.projectInfo?.deptTreeId,
        roadId: store.projectInfo?.roadId,
        slopeDamageType: 1,
        projectId,
        picList: [],
        videoList: [],
        name: "",
        longitude: "",
        latitude: ""
      };
      this.isSlopeDamageType()
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    /**
     * row  当前操作行的对象
     */
    handleEdit(row) {
      this.activeName = '监测对象信息'
      if(row.startTime){
        this.timerArray = [row.startTime, row.endTime];
      }
      this.currentRow = JSON.parse(JSON.stringify(row));
      this.currentRow.videoList = this.currentRow.videoList || []
      this.isSlopeDamageType('1')
      this.isShowDialog = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
  },

  created() {

  },
};
</script>

<style lang="less" scoped>
  /deep/ .el-collapse-item__header {
    background-color: #979797;
    margin-top: 20px;
    color: white;
    font-size: 20px;
    height: 40px;
    border-radius: 10px;

  }

  .work-point-form {

    .el-form-item {
      color: #1990FE;
    }
  }

  .pileInfo_wrap {
    display: flex;

    .left,
    .right {
      flex: 1;
      display: flex;

      .label {
        width: 40px;
        text-align: center;
      }

      .el-input:nth-of-type(1) {
        margin-right: 10px;
        flex: 1;
      }

      .el-input:nth-of-type(2),
      .el-input:nth-of-type(3) {
        flex: 0 0 80px;
      }
    }

    .middle {
      flex: 0 0 40px;
      text-align: center;
    }
  }

  .imgFrom {
    /deep/ .el-table td, .el-table th {
      padding: 2px 0;
      font-size: 13px;
    }

    .el-form-item {
      width: 100%;
      margin-bottom: 0px;

      .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: auto;
      }
    }
  }

  .delete_button {
    color: #ff4d51;
  }

  .up_button {
    color: #007cfd;
  }

  .top_button {
    color: #6fb825;
  }
</style>
